package com.run.motion.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.run.motion.config.IpConfig;
import com.run.motion.config.RuoYiConfig;
import com.run.motion.config.WXConfig;
import com.run.motion.entity.User;
import com.run.motion.service.UserService;
import com.run.motion.util.FileUploadUtils;
import com.run.motion.util.page.AjaxResult;
import com.run.motion.util.page.TableDataInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * 用户数据Controller
 *
 * @author lyq
 * @date 2022-03-24
 */
@Api(tags = "用户类接口")
@RestController
@RequestMapping("/user")
public class UserController extends BaseController{
    @Autowired
    private UserService userService;

    @Autowired
    private WXConfig wxConfig;

    @Autowired
    private IpConfig ipConfig;

    /***
     * 用户登录
     */
    @ApiOperation(value = "用户登录")
    @GetMapping("/login")
    public AjaxResult login(@RequestParam String code,@RequestParam String nickname) {
    //  1.接收wx用户登录的code
    //  2.调用auth.code2Session接口，获取openid和session_key
        JSONObject jsonObject = getWXOpenId(code,wxConfig.getAppid(),wxConfig.getSecret());
    //  3.处理业务逻辑，判断openid是否注册，在表中记录为pid
        String openid = jsonObject.getString("openid");
        if (userService.selectUserByUserPId(openid)==null){ // 新用户，注册
            User user = new User();
            user.setPid(openid);
            user.setNickName(nickname);
            user.setSex("未知");
            userService.insertUser(user); // 注册

            return new AjaxResult(201,"新用户注册成功",userService.selectUserByUserPId(openid));
        }
    //  4.返回登录结果
        User user = userService.selectUserByUserPId(openid);
        user.setAvatar(ipConfig.getIp()+user.getAvatar());
        return new AjaxResult(200,"登录成功",user); // 返回用户数据
    }
//    去微信服务器验证
    private JSONObject getWXOpenId(String code,String appid,String secret){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret +
                "&js_code=" + code;
        JSONObject jsonObject = null;
        try {
            CloseableHttpClient client = HttpClientBuilder.create().build(); // 构建一个Client
            HttpGet get = new HttpGet(url); // 构建一个get请求
            CloseableHttpResponse response = client.execute(get); // 提交get请求
            HttpEntity result = response.getEntity(); // 拿到返回的HttpResponse的实体
            InputStream inputStream = result.getContent(); // 拿到实体里的内容
            StringBuilder sb = new StringBuilder(); // 对输入流进行处理
            String content;
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            while ((content = br.readLine()) != null) { // 转成字符串
                sb.append(content);
            }
            String str = sb.toString();
            jsonObject = JSON.parseObject(str); // 把字符串转为json对象
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 头像上传
     */
    @ApiOperation(value = "头像上传")
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("file") MultipartFile file,
                             @RequestParam("pid") String pid) throws IOException
    {
        if (!file.isEmpty())
        {
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
            if (userService.updateUserAvatar(pid, avatar))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("avatar", ipConfig.getIp()+avatar);
                return ajax;
            }
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }
    /**
     * 查询用户数据列表
     */
    @ApiOperation(value = "查询用户数据", notes = "可以后面跟参数：?pageNum=1&?pageSize=10")
    @GetMapping("/list")
    public TableDataInfo list()
    {
        startPage();
        List<User> list = userService.selectUserList();
        return getDataTable(list);
    }



    /**
     * 获取用户数据详细信息
     */
    @ApiOperation(value = "获取用户数据详细信息")
    @GetMapping(value = "/{pid}")
    public AjaxResult getInfo(@PathVariable("pid") String pid)
    {
        return AjaxResult.success(userService.selectUserByUserPId(pid));
    }

    /**
     * 新增用户数据
     */
    @ApiOperation(value = "新增用户数据")
    @PostMapping
    public AjaxResult add(@RequestBody User user)
    {
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户数据
     */
    @ApiOperation(value = "修改用户数据")
    @PutMapping
    public AjaxResult edit(@RequestBody User user)
    {
        if(userService.updateUser(user)>0){
            User user1 = userService.selectUserByUserPId(user.getPid());
            user1.setAvatar(ipConfig.getIp()+user1.getAvatar());
            return AjaxResult.success(user1);
        }
        return AjaxResult.error("修改失败");
    }

    /**
     * 删除用户数据
     */
    @ApiOperation(value = "删除用户数据")
    public AjaxResult remove(@PathVariable String[] pids)
    {
        return toAjax(userService.deleteUserByPIds(pids));
    }
}
